package com.wk.code.wkserver.manager;

import com.alibaba.fastjson.JSONObject;
import com.wk.code.wkserver.constant.Constant;
import com.wk.code.wkserver.response.app.WxSessionResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;


/**
 * @author: wangqiang
 * @create: 2021-08-19 15:28
 */
@Component
@Slf4j
public class WeixinManager {

    @Resource
    private RestTemplate restTemplate;

    @Value("${weixin.appId}")
    private String appId;

    @Value("${weixin.appSecret}")
    private String appSecret;

    /**
     * 通过code 获取openId
     *
     * @param code code
     * @return WxSessionResponse
     */
    public WxSessionResponse sessionCode(String code) {
        String url = String.format(Constant.WX_LOGIN_OPENID, appId, appSecret, code);
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        String body = entity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        WxSessionResponse session = new WxSessionResponse();
        session.setOpenId(jsonObject.getString("openid"));
        session.setSessionKey(jsonObject.getString("session_key"));
        return session;
    }

    /**
     * @param sessionKey    sessionKey
     * @param iv            iv
     * @param encryptedData encryptedData
     * @return String
     */
    public String getWxMiniPhone(String sessionKey, String iv, String encryptedData) throws Exception {
        byte[] encryptData = Base64Utils.decodeFromString(encryptedData);
        byte[] ivData = Base64Utils.decodeFromString(iv);
        byte[] key = Base64Utils.decodeFromString(sessionKey);
        String resultString = null;
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        resultString = new String(cipher.doFinal(encryptData), StandardCharsets.UTF_8);
        JSONObject object = JSONObject.parseObject(resultString);
        return object.getString("phoneNumber");
    }
}
